﻿using System;
using System.Linq;
using System.Runtime.Caching;
using System.Text.RegularExpressions;
using Turquoise.Caching.Abstract;
using Turquoise.Helpers;

namespace Turquoise.Caching.Microsoft
{

    public class MemoryCacheManager : ICacheManager
    {
        private readonly CacheItemPolicy _policy = new CacheItemPolicy
        {
            AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(ConfigurationHelper.GetAppSetting("CacheTimeOut").ConvertToInt())
        };


        protected ObjectCache Cache => MemoryCache.Default;
        public object Get(string key)
        {
            return Cache[key];
        }
        public virtual T Get<T>(string key)
        {
            return (T)Cache[key];
        }
        public virtual void Add(string key, object data)
        {
            if (data == null)
            {
                return;
            }
            Cache.Add(new CacheItem(key, data), _policy);
        }

        public void AddForce(string key, object data)
        {
            Cache.Add(new CacheItem(key, data), _policy);
        }

        public virtual bool IsAdd(string key)
        {
            return (Cache.Contains(key));
        }

        public virtual void Remove(string key)
        {
            Cache.Remove(key);
        }

        public virtual void RemoveByPattern(string pattern)
        {
            var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = Cache.Where(d => regex.IsMatch(d.Key)).Select(d => d.Key).ToList();

            foreach (var key in keysToRemove)
            {
                Remove(key);
            }
        }

        public virtual void Clear()
        {
            foreach (var item in Cache)
            {
                Remove(item.Key);
            }
        }
    }


}
